package com.jeeccm.modules.web.interceptors;

import com.google.common.collect.Maps;
import com.jeeccm.modules.core.exceptions.ErrorCode;
import com.jeeccm.modules.core.exceptions.ServiceException;
import com.jeeccm.modules.utils.SignatureUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springside.modules.utils.mapper.JsonMapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 类名：SignatureInterceptor.java<br>
 * 描述：参数验证<br>
 * @author ：XINJF<br>
 * 创建日期：2018年3月21日 下午5:03:49<br>
 * 版本：1.0<br>
 * 修改者：<br>
 * 修改日期：<br>
 */
public class SignatureInterceptor implements HandlerInterceptor {
	
	private static Logger logger = LoggerFactory.getLogger(SignatureInterceptor.class);
	
	private static final String SIGN_KEY = "26F72780372E84B6CFAED6F7B19139CC47B1912B6CAED753";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		System.out.println("signature.......");
		try {
			final String sign  = request.getHeader("X-JEECCM-SIGN");
			System.out.println("sign=="+sign);
			final String body = request.getParameter("body");
			System.out.println("body=="+body);
			if(StringUtils.isBlank(sign)) {
				throw new ServiceException("sign不能为空",ErrorCode.SIGN_ERROR);
			}
			if(StringUtils.isBlank(body)) {
				throw new ServiceException("body不能为空",ErrorCode.SIGN_ERROR);
			}
			final Map<String,String> paramMap = new HashMap<String,String>();
			paramMap.put("body", body);
			if(!SignatureUtil.isSignatureValid(paramMap,SIGN_KEY,sign)) {
				throw new ServiceException("签名验证失败",ErrorCode.SIGN_ERROR);
			}
		} catch (ServiceException e) {
			Map<String,Object> map = Maps.newHashMap();
			map.put("success","false");
	        map.put("msg",e.getMessage());
	        String json = JsonMapper.INSTANCE.toJson(map);
	        response.setHeader("content-type", org.springside.modules.web.MediaTypes.TEXT_HTML_UTF_8);
	        response.getWriter().print(json.toString());
	        return false;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

}
